<template>
  <el-dialog
    :title="title"
    :visible.sync="detailVisible"
    width="1200px"
    :close-on-click-modal="false"
  >
    <el-form :model="ruleForm" ref="ruleForm" label-width="100px" size="small">
      <el-row>
        <el-col :span="12">
            <el-form-item
              label="标题"
              prop="title"
              :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]"
            >
              <el-input v-model="ruleForm.title" placeholder="请输入标题"></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="公告类型"
            prop="noticeType"
            :rules="[{ required: true, message: '请选择公告类型', trigger: 'change' }]"
          >
            <el-select v-model="ruleForm.noticeType" style="width: 100%;" placeholder="请选择">
              <el-option
                v-for="item in classifyData"
                :key="item.name"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item
        label="通知内容"
        prop="content"
        :rules="[
          { required: true, message: '请输入通知内容', trigger: 'blur' }
        ]"
      >
        <quill-editor
          style="display: inline-block;width: 100%;height: 300px;"
          v-model="ruleForm.content"
          :options="editorOption"
          ref="footerRef"
        ></quill-editor>
      </el-form-item>
      <el-form-item
        label="发布范围"
        prop="publishRange"
        :rules="[
          { required: true, message: '请选择发布范围', trigger: 'change' }
        ]"
      >
        <el-radio-group v-model="ruleForm.publishRange" @change="rangeChange">
          <el-radio label="1">对指定人员开放</el-radio>
          <el-radio label="2">全部</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择人员">
        <el-tag
          v-for="tag in selectItem.slice(0, 5)"
          :key="tag.id"
          closable
          @close="handleUserClose(tag)"
        >
          {{ tag.name }}
        </el-tag>
        <template v-if="selectItem.length > 5">
          <el-popover placement="top" width="600" trigger="click">
            <el-tag
              v-for="tag in selectItem"
              :key="tag.id"
              closable
              @close="handleUserClose(tag)"
              style="margin:6px;"
            >
              {{ tag.name }}
            </el-tag>
            <el-button
              slot="reference"
              style="margin-right: 10px;"
              type="text"
              size="mini"
              >...查看更多</el-button
            >
          </el-popover>
        </template>

        <el-button
          type="primary"
          :disabled="ruleForm.publishRange === '2'"
          @click="checkUserClick"
          size="mini"
          >点击选择人员</el-button
        >
      </el-form-item>
      <el-form-item label="附件">
        <el-upload
          class="avatar-uploader"
          accept="image/*,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="fileList"
          :before-upload="beforeAvatarUpload"
          :on-remove="onRemove"
          action="#"
          :http-request="onChangeFile"
        >
          <el-button type="primary" size="mini">上传</el-button>
          <div
            slot="tip"
            style="display: inline-block;margin-left: 20px;"
            class="el-upload__tip"
          >
            支持图片、pdf、doc、docx格式
          </div>
        </el-upload>
      </el-form-item>
    </el-form>

    <el-dialog title="图片预览" append-to-body :visible.sync="img.visible">
      <img :src="img.previewUrl" alt="图片预览" class="previcew-img" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="img.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <Monthly ref="createMonthly" @onOk="onSuccess"></Monthly>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="detailVisible = false">取 消</el-button>
      <el-button
        size="small"
        :loading="loading"
        type="primary"
        @click="noticeSubmit('ruleForm')"
        >提交</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import { addNotice, updateNotice,getSupplierCategoryTree } from "@/api/supplier_api";
import { getDetailByKey} from "@/api/about_api";
import { toolbarOptions, handlers } from "@/utils/index";
import pdfimg from "@/assets/pdf_file.png";
import wordimg from "@/assets/word_file.png";
import Monthly from "./monthly.vue";
export default {
  components: {
    Monthly
  },
  data() {
    return {
      detailVisible: false,
      title: "",
      fileList: [],
      ruleForm: {
        attachment: "",
        content: "",
        noticeType:"",
        publishRange: "2",
        title: "",
        id: ""
      },
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: handlers
          }
        },
        theme: "snow"
      },
      img: {
        visible: false,
        previewUrl: ""
      },
      loading: false,
      selectItem: [],
      classifyData:[]
    };
  },
  computed: {
    ...mapGetters(["uploadType"])
  },
  methods: {
    ...mapActions({
      uploadFile: "user/uploadFile"
    }),
    openForm(row, arr) {
      this.fileList = [];
      this.selectItem = [];
      this.getInfo()
      if (typeof row == "boolean") {
        this.title = "新增公告";
        this.ruleForm.attachment = "";
        this.ruleForm.content = "";
        this.ruleForm.publishRange = "2";
        this.ruleForm.title = "";
        this.ruleForm.noticeType = ''
        this.ruleForm.id = "";
      } else {
        this.ruleForm = {
          attachment: "",
          content: row.content,
          publishRange: row.publishRange,
          title: row.title,
          noticeType:row.noticeType,
          id: row.id
        };
        if (row.attachment) {
          let arr = JSON.parse(row.attachment);
          this.fileList = arr;
        }
        if (arr.length && row.publishRange == "1") {
          let str = arr.filter(v => row.publishUserIds.includes(v.id));
          this.selectItem = str;
        }
        this.title = "修改公告";
      }
      this.detailVisible = true;
    },
    async getInfo() {
      const { code, data } = await getDetailByKey('tzfl');
        this.classifyData = []
        if (code === 200) { 
            if (data && data.value) {
              let arr = JSON.parse(data.value)
              this.classifyData = arr ?? []
            }
        }
    },
    async checkUserClick() {
      const { code, data } = await getSupplierCategoryTree()
      this.$refs.createMonthly.open(data)
    },
    onSuccess(arr) {
      const idx = this.selectItem.map(v => v.id)
      arr.forEach(v => {
        if (!idx.includes(v.id)) {
          this.selectItem.push(v)
        }
      })
      if (arr.length == 0) {
        this.selectItem = []
      }
    },
    handleUserClose(tag) {
      let idx = this.user.selectItem.findIndex(v => v.id == tag.id);
      if (idx !== -1) {
        this.user.selectItem.splice(idx, 1);
      }
    },
    rangeChange(e) {
      if (e == 2) {
        this.selectItem = []
      }
    },
    handlePreview(file) {
      if (file.type == 1) {
        window.open(file.urls);
      } else if(file.type == 2){
        this.img.previewUrl = file.url;
        this.img.visible = true;
      } else if (file.type == 3) {
        const link = document.createElement('a');
        link.href = file.urls;
        link.download = file.name;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },
    async onChangeFile(file, fileList) {
      let fileKey = this.uploadType["notice"];
      const url = await this.uploadFile({ fileKey: fileKey, data: file });
      if (url) {
        if (file.file.type == "application/pdf") {
          this.fileList.push({
            name: file.file.name,
            url: pdfimg,
            urls: url,
            type: 1
          });
        } else if (file.file.type == "application/msword") {
           this.fileList.push({
            name: file.file.name,
            url: wordimg,
            urls: url,
            type: 3
          });
        } else if (file.file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
           this.fileList.push({
            name: file.file.name,
            url: wordimg,
            urls: url,
            type: 3
          });
        } else {
           this.fileList.push({ name: file.file.name, url: url, type: 2 });
        }
      }
    },
    onRemove(file, fileList) {
      const index = this.fileList.indexOf(file);
      if (index > -1) {
        this.fileList.splice(index, 1);
      }
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "application/pdf" ||
        file.type === "application/msword" ||
        file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      if (!isJPG) {
        this.$message.error("附件支持 jpeg、png、jpg 、pdf、docx、doc格式!");
      }
      return isJPG;
    },
    noticeSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let param = {};
          if (this.ruleForm.publishRange === "1") {
            if (this.selectItem.length == 0) {
              this.$message.error("请选择指定人员");
              return;
            }
            let result = this.selectItem.map(v => v.id);
            param.publishUserIds = result.join(",");
            param.receivers = result;
          }
          if (this.fileList.length) {
            param.attachment = JSON.stringify(this.fileList);
          }
          if (this.ruleForm.id) {
            param.id = this.ruleForm.id;
          }
          param.publishRange = this.ruleForm.publishRange;
          param.title = this.ruleForm.title;
          param.content = this.ruleForm.content;
          param.noticeType = this.ruleForm.noticeType;
          this.loading = true;
          try {
            const { code, msg } = this.ruleForm.id ? await updateNotice(param) : await addNotice(param);
            if (code === 200) {
              this.$message.success(msg);
              this.$emit("onOk", true);
              this.detailVisible = false;
            }
          } finally {
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped></style>
<style>
.el-tag {
  margin-right: 10px;
}
</style>
